package com.dbsync.core;

import com.dbsync.exception.DbsyncException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * 数据库工具类
 */
public class DBUtil {
    // 配置文件对象
    private Config config;

    /**
     * 初始化
     * @throws Exception
     */
    public void init() throws Exception {
        this.config = ConfigLoader.init();
    }

    /**
     * 获取任务集合
     * @return
     */
    public List<Target> getTargets() {
        return this.config.getTargets();
    }

    /**
     * 获取源数据库连接
     * @return 返回connection对象
     * @throws Exception
     */
    public Connection getDBConnection() throws Exception {
        Database database = this.config.getDatabase();
        Class.forName(database.getDriverClassName());
        return DriverManager.getConnection(
                database.getUrl(),
                database.getUsername(),
                database.getPassword()
        );
    }

    /**
     * 获取任务数据库连接
     * @param index 任务索引
     * @return 返回connection对象
     * @throws Exception
     */
    public Connection getTargetConnection(int index) throws Exception {
        Target target = this.config.getTargets().get(index - 1);
        Class.forName(target.getDriverClassName());
        return DriverManager.getConnection(
                target.getUrl(),
                target.getUsername(),
                target.getPassword()
        );
    }

    /**
     * 获取数据库类型
     * @param index 任务索引
     * @return 返回对应数据库类型
     * @throws DbsyncException
     */
    public String getDBType(int index) throws DbsyncException{
        if (index < 1) {
            return this.config.getDatabase().getType();
        } else {
            return this.config.getTargets().get(index - 1).getType();
        }
    }
}